﻿var MessageGrid = MessageGrid || {};
MessageGrid = function () {
    var gridInEditMode = false;
    var scratchDropDownChanged = false;
    var MessageGridDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/CommunicationMessageGrid/GetCommunicationMessages",
                type: "get",
                 cache: false,
                dataType: "json"
            },


            create: {

                url: "/CommunicationMessageGrid/CreateMessage",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"

            },
            update: {
                url: "/CommunicationMessageGrid/UpdateMessage",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            destroy: {
                url: "/CommunicationMessageGrid/DeleteMessage",
                type: "POST",
                dataType: "json",
                contentType: "application/JSON"
            },
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }

        },

        pageSize: 5,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },
                    followUpDate: {
                        type: "string",
                        validation: { required: true }
                    },
                    contactID:{
                        type: "string"
                    },
                    office:{
                     type: "string"
                    },
                    product: {
                        type: "string"
                    },

                    communication: {
                        type: "string"
                    },

                    assignedEmployeeID: {
                        type: "string"
                    },

                    email: {
                        type: "string"
                    },

                    phone: {
                        type: "string"
                    },

                    statusID: {
                        type: "string"
                    },

                    emailSubject: {
                        type: "string"
                    },

                    notes: {

                        type: "string",
                        validation: { required: true }
                    },

                    error: function (a) {
                        $('#MessageGrid').data("kendoGrid").cancelChanges();
                    },

                }
            }
        }

    });

    var products = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetAllProducts/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }

        },
        requestEnd: function (a, b) {
           
        }
    });
    var contactedVia = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetAllCommunicationMedium/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        },
        requestEnd: function (a, b) {

        }
    });
    var status = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetStatus/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
       var offices = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/CompanyOffice/GetAllCompanyOffice/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });

    return {
        MessageGridDataSource: MessageGridDataSource,
        gridInEditMode: gridInEditMode,
        products: products,
        contactedVia: contactedVia,
        status: status,
        offices:offices,
        scratchDropDownChanged: scratchDropDownChanged
    }
}();

$(function () {

    $(window).on("beforeunload", function () {
        if (JobGrid.gridInEditMode) {
            return "Are you sure you want to discard all your changes."
        }

    });
    $("#MessageGrid").kendoGrid({
        dataSource: MessageGrid.MessageGridDataSource,
        scrollable: true,
        height: "250px",
        toolbar: ["create"], //, "save", "cancel"],
        pageable: true,
        height: 300,
        columns: [
      {
          field: "followUpDate", title: "Follow UpDate", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
          editor: dateTimeEditor,
          filterable: {
              ui: "datetimepicker"
          }
      },
         { field: "name", title: "Contact", filterable: false, width: "8em" },
          { field: "companyoffice", title: "Office", editor:officeDropDownEditor, width: "8em" },
          { field: "product", title: "Products", filterable: false, width: "8em" },
          { field: "commVia", title: "Contacted Via", width: "8em" },
       { field: "assignedEmployeeID", title: "Assigned Employee", filterable: false, width: "8em" },
       { field: "phone", title: "Phone", width: "8em" },
       { field: "email", title: "Email", filterable: false, width: "8em" },
       { field: "statusName", title: "Status", filterable: false, width: "8em" },
      { field: "subject", title: "Subject", width: "8em" },
        { field: "notes", title: "Notes", width: "8em" },    
      {
          title: "&nbsp;",
          width: "25em",
          //command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {
                      
                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      //see what is coming in dataItem
                      //if (dataItem > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                          deleteTopicConfirmation(e, this);
                      ////}
                      return false;
                  }
              }
          ]
      }
        ],
        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                     contains:"Contains"
                }
            }
        },

        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },
        selectable: true,
        // change: onTopicChange,
        // dataBound: onTopicsGridDataBound,
      
        cancel: function () {
            MessageGrid.gridInEditMode = false;
        }
    });

    MessageGrid.MessageGridDataSource.bind("requestEnd", showSuccessMessage);

    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            MessageGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();
        }
    }

    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });

      function productDropDownEditor(container, options) {
      
        $('<input id="ProductValue" data-text-field="product" data-value-field="product"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "product",
            dataTextField: "product",
            dataSource:MessageGrid.product
        .products
        });
    }
    function statusDropDownEditor(container, options) {
      
        $('<input id="StatusValue" data-text-field="statusName" data-value-field="statusName"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "statusName",
            dataTextField: "statusName",
            dataSource: MessageGrid.status
          
        });
    }
    function contactedviaDropDownEditor(container, options) {
       
        $('<input id="ContactedViaValue" data-text-field="commVia" data-value-field="commVia"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "commVia",
            dataTextField: "commVia",
            dataSource: 
                MessageGrid.contactedVia
            
        });
    }

    function officeDropDownEditor(container, options) {
      
        $('<input id="officeId" data-text-field="companyoffice" data-value-field="companyoffice"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "companyoffice",
            dataTextField: "companyoffice",
            dataSource:
                MessageGrid.office

        });
    }

    function deleteTopicConfirmation(e, widget) {
        var grid = $('#MessageGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

});